package com.ruoyi.system.utils;

import com.ruoyi.system.domain.XmlGenerate;
import org.springframework.beans.factory.annotation.Value;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.FileOutputStream;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import static com.ruoyi.system.utils.AESEncryption.*;

public class GenerateXML {

    @Value("${xmlfile.generate-save}")
    private static String directoryPath;

    public static String generateXML(XmlGenerate generate) {

        try {
            Date currentDate = new Date();
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(currentDate);
            calendar.add(Calendar.DAY_OF_MONTH, 7); // 加7天
            Date newDate = calendar.getTime();

            SecretKey secretKey = KeyGenerator.getInstance("AES").generateKey();
            byte[] keyBytes = secretKey.getEncoded();

            // 转换为十六进制字符串
            String hexKey = byteArrayToHexString(keyBytes);
            System.out.println("Generated AES Key (Hex): " + hexKey);

            // 从十六进制字符串转换回字节数组
            byte[] recoveredKeyBytes = hexStringToByteArray(hexKey);

            // 使用字节数组生成 AES 密钥
            SecretKey recoveredSecretKey = new SecretKeySpec(recoveredKeyBytes, "AES");

            // 打印恢复的 AES 密钥（可选）
            System.out.println("Recovered AES Key (Hex): " + byteArrayToHexString(recoveredSecretKey.getEncoded()));

            // 比较原始密钥和恢复的密钥
            System.out.println(recoveredSecretKey);
            System.out.println("Keys are equal: " + secretKey.equals(recoveredSecretKey));
            // 创建文档构建器
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.newDocument();

            // 创建根元素
            Element root = document.createElement("License");
            document.appendChild(root);

            // 创建Header元素
            Element header1 = document.createElement("Header");
            header1.setAttribute("username", "hebeishooting@163.com");
            header1.setAttribute("name", generate.getUsername());
            header1.setAttribute("licensee", "河北省体育局射击射箭运动中心");
            header1.setAttribute("shootingrange", "河北省");
            header1.setAttribute("country", "China");
            header1.setAttribute("email", "hebeishooting@163.com");
            header1.setAttribute("licensecode", "");
            header1.setAttribute("creationdate", "21.08.2023 05:06:07");
            root.appendChild(header1);

            Element header2 = document.createElement("Header");
            header2.setAttribute("creationdate", currentDate.toString());
            root.appendChild(header2);

            // 创建Championship元素
            Element championship = document.createElement("Championship");
            championship.setAttribute("name", generate.getLicenseName());
            championship.setAttribute("startdate", String.valueOf(generate.getStartDate()));
            championship.setAttribute("enddate", String.valueOf(generate.getEndDate()));
            championship.setAttribute("level", String.valueOf(generate.getLevel()));
            championship.setAttribute("type", String.valueOf(generate.getType()));
            root.appendChild(championship);

            // 创建Release元素
            Element release = document.createElement("Release");
            release.setAttribute("actualrelease", "1");
            release.setAttribute("actualsubrelease", "0");
            root.appendChild(release);

            // 创建XmlProperties元素
            Element xmlProperties = document.createElement("XmlProperties");
            root.appendChild(xmlProperties);

            // 添加XmlProperty元素
            String[][] properties = {
                    {"matchname", generate.getMatchName()},
                    {"10Meter", String.valueOf(generate.isMeter10())},
                    {"25Meter", String.valueOf(generate.isMeter25())},
                    {"25RFP", String.valueOf(generate.isMeter25RFP())},
                    {"50Meter", String.valueOf(generate.isMeter50())},
                    {"shotgun", String.valueOf(generate.isShotgun())},
                    {"archery", String.valueOf(generate.getArchery() == 1?true:false)},
            };
            List<Boolean> results = Arrays.asList(
                    generate.isMeter10(),
                    generate.isMeter25(),
                    generate.isMeter25RFP(),
                    generate.isMeter50(),
                    generate.isShotgun(),
                    generate.getArchery() == 1?true:false
            );

            String gameControl = "";
            for (Boolean result : results) {
                if (result) {
                    gameControl = gameControl + "1";
                }else {
                    gameControl = gameControl + "0";
                }
            }

            for (String[] property : properties) {
                Element xmlProperty = document.createElement("XmlProperty");
                xmlProperty.setAttribute("name", property[0]);
                xmlProperty.setAttribute("value", property[1]);
                xmlProperties.appendChild(xmlProperty);
            }

            // 创建Signature元素
            Element signature = document.createElement("Signature");
            signature.setAttribute("xmlns", "http://www.w3.org/2000/09/xmldsig#");
            root.appendChild(signature);

            // 添加SignedInfo元素
            Element signedInfo = document.createElement("SignedInfo");
            signature.appendChild(signedInfo);

            // 添加CanonicalizationMethod元素
            Element canonicalizationMethod = document.createElement("CanonicalizationMethod");
            canonicalizationMethod.setAttribute("Algorithm", "http://www.w3.org/TR/2001/REC-xml-c14n-20010315");
            signedInfo.appendChild(canonicalizationMethod);

            // 添加SignatureMethod元素
            Element signatureMethod = document.createElement("SignatureMethod");
            signatureMethod.setAttribute("Algorithm", "http://www.w3.org/2000/09/xmldsig#rsa-sha1");
            signedInfo.appendChild(signatureMethod);

            // 添加Reference元素
            Element reference = document.createElement("Reference");
            reference.setAttribute("URI", "");
            signedInfo.appendChild(reference);

            // 添加Transforms元素
            Element transforms = document.createElement("Transforms");
            reference.appendChild(transforms);

            // 添加Transform元素
            Element transform = document.createElement("Transform");
            transform.setAttribute("Algorithm", "http://www.w3.org/2000/09/xmldsig#enveloped-signature");
            transforms.appendChild(transform);

            // 添加DigestMethod元素
            Element digestMethod = document.createElement("DigestMethod");
            digestMethod.setAttribute("Algorithm", "http://www.w3.org/2000/09/xmldsig#sha1");
            reference.appendChild(digestMethod);

            // 添加DigestValue元素
            Element digestValue = document.createElement("DigestValue");
            digestValue.setTextContent(byteArrayToHexString(recoveredSecretKey.getEncoded()));
            reference.appendChild(digestValue);

            // 添加SignatureValue元素


            String originalText = "StartTime:" + generate.getStartDate() + "EndTime:" + generate.getEndDate() + "name:" + generate.getUsername() + " GameControl:" + gameControl;
            String encryptedText = encrypt(originalText, secretKey);
            Element signatureValue = document.createElement("SignatureValue");
            signatureValue.setTextContent(encryptedText);
            signature.appendChild(signatureValue);

            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");

            LocalDate currentDay = LocalDate.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String formattedDate = currentDay.format(formatter);
            String fileName = generate.getUsername() + formattedDate + "Credentials.xml";

            File xmlFile = new File(directoryPath, fileName);
            try (FileOutputStream fileOutputStream = new FileOutputStream(xmlFile)) {
                StreamResult result = new StreamResult(fileOutputStream);
                DOMSource source = new DOMSource(document);
                transformer.transform(source, result);
            }
            System.out.println("XML 文件已保存为: " + xmlFile.getAbsolutePath());
            return xmlFile.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "";
    }
}
